package com.cloudtasks;
import com.cloudtasks.R;
import android.app.Activity;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CursorTreeAdapter;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorTreeAdapter;
import android.widget.TextView;

/**
 * @author Administrator
 * 
 */

public class GroceryGroupsDisplayPage1Activity extends TabGroupActivity {

	String UserName = "";
	long UserID;
	String ListName = "";
	long ListID;
	final Context myContext = this;
	//private Cursor DBcursor;
	Cursor itemsCursor;
	final static String TYPE_PAGE = "type";
	private Database mDb;
	MyExpandableListAdapter mAdapter;
	
	public class MyExpandableListAdapter extends SimpleCursorTreeAdapter {
		
		//private Cursor mycursor = mDb.fetchAllItemTypesByList(lid);
		private long ListId;
		// Note that the constructor does not take a Cursor. This is done to
		// avoid querying the
		// database on the main thread.
		public MyExpandableListAdapter(Context context, int groupLayout,
				int childLayout, String[] groupFrom, int[] groupTo,
				String[] childrenFrom, int[] childrenTo, long lid) {

			// fetchAllItemTypesByList(long ListId)
			//mycursor = mDb.fetchAllItemTypesByList(lid);
			super(context, mDb.fetchAllItemTypesByList(lid), groupLayout,
					groupFrom, groupTo, childLayout, childrenFrom, childrenTo);
			
			ListId = lid;
			
			
			
		}

		public void resume()
		{
			if(mDb!=null)
				changeCursor(mDb.fetchAllItemTypesByList(ListId));
		}
		@Override
		protected Cursor getChildrenCursor(Cursor groupCursor) {
			// Given the group, we return a cursor for all the children within
			// that group

			// Return a cursor that points to this contact's phone numbers
			// Uri.Builder builder = Contacts.CONTENT_URI.buildUpon();
			// ContentUris.appendId(builder,
			// groupCursor.getLong(GROUP_ID_COLUMN_INDEX));
			// builder.appendEncodedPath(Contacts.Data.CONTENT_DIRECTORY);
			// Uri phoneNumbersUri = builder.build();

			// mQueryHandler.startQuery(TOKEN_CHILD, groupCursor.getPosition(),
			// phoneNumbersUri,
			// PHONE_NUMBER_PROJECTION, Phone.MIMETYPE + "=?",
			// new String[] { Phone.CONTENT_ITEM_TYPE }, null);
			int type_column = groupCursor.getColumnIndex(Database.KEY_TYPE);
			// groupCursor.moveToFirst();
			// MyTools.displayToastMessage(myContext,
			// groupCursor.getString(type_column));
			itemsCursor = mDb.fetchAllItemsInListByType(ListID,groupCursor.getString(type_column));
            //startManagingCursor(itemsCursor);
            return itemsCursor;
			
		}

		@Override
		protected void bindChildView(View view, Context context, Cursor cursor,
				boolean isLastChild) {
			//create new view binder and set
			ViewBinder temp = getViewBinder();
			 setViewBinder(new MyExpandableListAdapter.ViewBinder() {
		            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
		              final int nCheckedIndex = cursor.getColumnIndex(Database.KEY_CHECKED);
		              if (columnIndex == nCheckedIndex) {
		                CheckBox cb = (CheckBox) view;
		                boolean bChecked = (cursor.getInt(nCheckedIndex) != 0);
		                cb.setChecked(bChecked);
		                cb.setOnCheckedChangeListener(
		                        new CompoundButton.OnCheckedChangeListener() {
		                         public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
		                         // update your value in the db
		                        	 try{
		                        		 ExpandableListView lv = (ExpandableListView) findViewById(R.id.expandableListView1);	                        	 
			                        	 int pos = lv.getPositionForView(buttonView);
			                        	 long group_pos = lv.getExpandableListPosition(pos);
			                        	 
			                        	 MyExpandableListAdapter temp2 = (MyExpandableListAdapter)lv.getExpandableListAdapter();
			                        	  long id = temp2.getChildId(ExpandableListView.getPackedPositionGroup(group_pos) , ExpandableListView.getPackedPositionChild(group_pos));
			                        	 boolean success = mDb.updateItemCheckedState(id, isChecked);
			                        	 if (success == false)
			                        	 {
			         						MyTools.displayToastMessage(myContext,
			         								"Error: could not update");
			                        	 MyTools.displayToastMessage(myContext,
			         								String.valueOf(id));
			                        	 }
			         					else
			         						MyTools.displayToastMessage(myContext,
			         								"Successfully " + (isChecked?("Checked"):("Unchecked")));
		                        	 }
		                             catch(Exception e){
		                             	//MyTools.displayToastMessage(myContext, e.toString());
		                             }	                      
		                             }});
		                return true;
		              }
		              return false;
		            }
		          });
			 
			 super.bindChildView(view, context, cursor, isLastChild);
			 setViewBinder(temp);
		}
	
	}
		
	

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// MyTools.displayToastMessage(myContext,
		// "Do I get here?");
		setContentView(R.layout.expandable_item_page);
		// setContentView(R.layout.tab_list_itempage);
		 Button addItem = (Button)findViewById(R.id.item_edit_button);
		 addItem.setOnClickListener(editItemListener);

		try {
			// Unwrap parameters from last activity: the User's name
			// and also his User ID
			Bundle param = getIntent().getExtras();
			if (param != null) {
				UserName = param.getString("uname");
				UserID = param.getLong("uid");
				ListName = param.getString("listname");
				ListID = param.getLong("lid");
			}

			// initialize the Database for this context
			mDb = new Database(this);
			mDb.open();

			ExpandableListView elv = (ExpandableListView) findViewById(R.id.expandableListView1);
			// ListView lv = (ListView) findViewById(R.id.types_listview);
			// DBcursor = mDb.fetchAllItemTypesByList(ListID);
			// DBcursor = mDb.fetchAllItemsInListByType(ListID, "Fruit");
			/*
			 * lv.setAdapter(new SimpleCursorAdapter(this,
			 * android.R.layout.simple_list_item_1, DBcursor, new String[]
			 * {Database.KEY_TYPE}, new int[] { android.R.id.text1} ));
			 */
			// startManagingCursor(DBcursor);

			
			// Set up our adapter
			mAdapter = new MyExpandableListAdapter(this,
					android.R.layout.simple_expandable_list_item_1,
					R.layout.single_item_checkbox,
					new String[] { Database.KEY_TYPE }, // Name for group layouts
					new int[] { android.R.id.text1 }, 
					new String[] {Database.KEY_CHECKED, Database.KEY_GROC_NAME }, // Name for child layout
					new int[] { R.id.CheckBox1, R.id.text1 }, 
					ListID);
			
		    
			// DBcursor = mDb.fetchAllItemsInListByType(ListID, TypeName);
			// DBcursor = mDb.fetchAllItemsInListByType(ListID, "Fruit");
			/*
			 * SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,
			 * R.layout.single_item_checkbox, DBcursor, new String[]
			 * {Database.KEY_CHECKED, Database.KEY_GROC_NAME}, new int[] {
			 * R.id.CheckBox1, R.id.text1} );
			 */

			elv.setAdapter(mAdapter);
			
			int count = elv.getExpandableListAdapter().getGroupCount() ;
			for(int i=0; i<count;++i)
			{
				elv.expandGroup(i);
			}

			// what happens when you click one entry in the ListView
			/*
			 * lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			 * 
			 * @Override public void onItemClick(AdapterView<?> av, View view,
			 * int pos, long id) { String name = ((TextView)
			 * view).getText().toString();
			 * //MyTools.displayToastMessage(myContext, name); Intent intent =
			 * new Intent(myContext, GroceryGroupsDisplayPage2Activity.class);
			 * intent.putExtras(getIntent().getExtras());
			 * intent.putExtra("tname", name); TabGroupActivity parentActivity =
			 * (TabGroupActivity)getParent();
			 * parentActivity.startChildActivity("GroceryGroupsDisplayPage2Activity"
			 * , intent); } });
			 */
		} catch (Exception e) {
			MyTools.displayToastMessage(myContext, e.toString());
		}
	}

	private OnClickListener editItemListener = new OnClickListener() {
		public void onClick(View v) {
			// fetch the name of the user
			try {
				go_edit();
														
				
			} catch (Exception e) {
				MyTools.displayToastMessage(myContext, e.toString());
			}
		}
	};

	public void go_edit()
	{
		try{
			Intent intent = new Intent(myContext, GroceryGroupsEditActivity.class);
			intent.putExtras(getIntent().getExtras());
			TabGroupActivity parentActivity = (TabGroupActivity)getParent();
			parentActivity.startChildActivity("GroceryGroupsEditActivity", intent);
			//startActivity(intent);
		}
		catch(Exception e){
			MyTools.displayToastMessage(myContext,e.toString());	
		}
		
			
	}
	@Override
	public synchronized void onResume() {
		super.onResume();
		mAdapter.resume();
		 //DBcursor.requery();
		
	}

	public void onDestroy() {
		super.onDestroy();

		mDb.close();
	}
}
